<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <span style="line-height: 34px">标题：</span>
          <NInput
            placeholder="输入标题"
            v-model:value="form.title"
            style="width: 150px; margin-right: 20px"
          />
          <!-- <span style="line-height: 34px">审核状态：</span>
          <NSelect
            :options="auditFlagOption"
            v-model:value="form.auditFlag"
            placeholder="请选择状态"
            clearable
            style="width: 150px; margin-right: 20px"
          /> -->
          <span style="line-height: 34px">上架状态：</span>
          <NSelect
            :options="listFlagOption"
            v-model:value="form.listFlag"
            placeholder="请选择状态"
            clearable
            style="width: 150px; margin-right: 20px"
          />
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px"
              ghost
              @click="queryTableData(true)"
              :loading="tableLoading"
            >
              查询
            </NButton>
            <NButton
              style="width: 78px;margin-left: 15px;"
              @click="resetForm"
              ghost
              type="primary"
            >
              重置
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAdd"
          >
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
      />
    </template>
    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
  <NModal :auto-focus="false" v-model:show="detailVisible">
    <VDialogContent
      @close="detailVisible = false"
      title="公告预览"
      :action="false"
    >
      <div class="previewView">
        <div class="noticeBox">
          <div class="previewViewContent" v-html="contentDetail"></div>
          <!-- <div class="previewViewFooter">成为志愿者</div> -->
        </div>
      </div>
      <NSpace justify="center">
        <div class="modal-card__action" style="padding-top: 10px;">
          <NButton
            style="width: 78px"
            type="primary"
            @click="detailVisible = false"
          >
          关闭
          </NButton>
        </div>
      </NSpace>
    </VDialogContent>
  </NModal>
  <NModal :auto-focus="false" v-model:show="visible">
    <VDialogContent
      @close="visible = false"
      @submit="againChange"
      title="提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{type == 'up' ? '确认上架该公告吗?' : '确认下架该公告吗?'}}
      </div>
    </VDialogContent>
  </NModal>
  <NModal :auto-focus="false" v-model:show="modal">
    <VDialogContent
      @close="modal = false"
      @submit="againAction"
      title="提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{action == 'up' ? '确认上移该公告吗?' : '确认下移该公告吗?'}}
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import {
  NPopconfirm,
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NSelect,
  NTag,
  NIcon,
  NImage
} from 'naive-ui'
import FixedAction from '@/components/FixedAction.vue'
import VBackImg from '@/assets/images/back.png'
import { onActivated, onMounted, reactive, ref, h ,watch} from 'vue'
import { sendRequest } from '@/utils/api'
import type { volunteerModel } from '@/api/volunteer'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowUp, ArrowDown } from '@vicons/ionicons5';

const message = useMessage()
const router = useRouter()
const visible = ref(false);
const modal = ref(false);
const type = ref('');
const action = ref('');
const auditFlagOption = ref([
  {
    label: '未审核',
    value: 0
  },
  {
    label: '已审核',
    value: 1
  }
])
const listFlagOption = ref([
  {
    label: '未上架',
    value: 0
  },
  {
    label: '已上架',
    value: 1
  }
])
onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})

const tableData = ref<volunteerModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const modalVisible = ref(false)
const detailVisible = ref(false)
const route = useRoute()
const [form, resetForm] = useQueryForm(
  reactive({
    auditFlag: null,
    listFlag: null,
    title: null
  }),
  () => {
    form.auditFlag = null
    form.listFlag = null
    form.title = null
  }
)
const contentDetail = ref('');
const columns: DataTableColumns<volunteerModel> = [
  {
    title: '标题',
    key: 'title',
    width: '10rem',
    align: 'center'
  },
  {
    title: '开始时间',
    key: 'startDate',
    width: '10rem',
    align: 'center'
  },
  {
    title: '结束时间',
    key: 'endDate',
    width: '10rem',
    align: 'center'
  },
  {
    title: '报名截止时间',
    key: 'endEnrollDate',
    width: '10rem',
    align: 'center'
  },
  {
    title: '最后一次编辑时间',
    key: 'updateTime',
    width: '10rem',
    align: 'center'
  },
  // {
  //   title: '审核状态',
  //   key: 'statusName',
  //   width: '10rem',
  //   align: 'center',
  //   render: (row: any) => {
  //     let name = '';
  //     row.auditFlag == 1 ? name = '已审核' : name = '未审核'
  //     return h(
  //       NTag,
  //       {
  //         style: {
  //           marginRight: '6px'
  //         },
  //         type: 'info',
  //         bordered: false
  //       },
  //       {
  //         default: () => name
  //       }
  //     )
  //   }
  // },
  {
    title: '上架状态',
    key: 'statusName',
    width: '10rem',
    align: 'center',
    render: (row: any) => {
      let name = '';
      row.listFlag == 1 ? name = '已上架' : name = '未上架'
      return h(
        NTag,
        {
          style: {
            marginRight: '6px'
          },
          type: 'info',
          bordered: false
        },
        {
          default: () => name
        }
      )
    }
  },
  {
    title: '排序',
    key: 'action',
    width: '20rem',
    align: 'center',
    render: (row: any) => {
      return [
        h(
          NButton,
          {
            quaternary: true,
            circle: true,
            size: "small",
            style: {
              marginLeft: "20px",
            },
            onClick: () => handleChangeSort(row.id, 'up'),
          },
          { icon: () => h(NIcon, null, { default: () => h(ArrowUp) }) }
        ),
        h(
          NButton,
          {
            quaternary: true,
            circle: true,
            size: "small",
            style: {
              marginLeft: "20px",
            },
            onClick: () => handleChangeSort(row.id, 'down'),
          },
          { icon: () => h(NIcon, null, { default: () => h(ArrowDown) }) }
        )
      ]
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (row: any) => {
      let name = '';
      row.listFlag == 1 ? name = '下架' : name = '上架'
      if (row.listFlag == 0) {
        return [
          h(
            NButton,
            {
              type: 'primary',
              quaternary: true,
              onClick: () => handleEdit(row)
            },
            {
              default: () => '编辑'
            }
          ),
          h(
            NButton,
            {
              type: 'info',
              quaternary: true,
              onClick: () => handlePreview(row)
            },
            {
              default: () => '预览'
            }
          ),
          h(
            NButton,
            {
              type: 'error',
              quaternary: true,
              onClick: () => handleDelete(row.id)
            },
            {
              default: () => '删除'
            }
          ),
          // h(
          //   NPopconfirm,
          //   {
          //     positiveButtonProps: {
          //       size: 'tiny',
          //       color: '#007293',
          //       bordered: true,
          //     },
          //     negativeButtonProps: {
          //       size: 'tiny',
          //       color: '#007293',
          //       bordered: true,
          //     },
          //     onPositiveClick: (e: any) => {
          //       handleDelete(row.id)
          //     }
          //   },
          //   {
          //     trigger: () => {
          //       return h(
          //         NButton,
          //         {
          //           type: 'error',
          //           quaternary: true,
          //         },
          //         { default: () => '删除' }
          //       )
          //     },
          //     default: () => {
          //       return '确认删除该公告吗？'
          //     }
          //   }
          // ),06865B
          h(
            NButton,
            {
              color: row.listFlag == 1 ? '#06865B' : '#D9534F',
              type: 'warning',
              quaternary: true,
              onClick: () => handleListFlagStatus(row)
            },
            {
              default: () => name
            }
          ),
        ]
      }
      else {
        return [
          h(
            NButton,
            {
              type: 'info',
              quaternary: true,
              onClick: () => handlePreview(row)
            },
            {
              default: () => '预览'
            }
          ),
          h(
            NButton,
            {
              type: 'warning',
              quaternary: true,
              onClick: () => handleListFlagStatus(row)
            },
            {
              default: () => name
            }
          ),
        ]
      }
    }
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<volunteerModel>>({
    module: 'volunteer',
    api: 'list',
    override: {
      params: {
        title: form.title,
        auditFlag: form.auditFlag,
        listFlag: form.listFlag,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}

const handleEdit = (e: any) => {
  router.push({
    name: 'VolunteerRecruitNoticeEdit',
    query: { id: e.id }
  })
}

const handlePreview = async(e: any) => {
  const [error, res] = await sendRequest<HttpResponsePagination<any>>({
    module: 'volunteer',
    api: 'info',
    uri: {
      id: e.id
    }
  })
  if (error) throw new Error(error.message)
  if (res.code !== 0) throw new Error(res.msg)
  console.log('res', res)
  if (res.code == 0) {
    contentDetail.value = res.data.noticeContent
  }
  detailVisible.value = true;
}

const handleDetail = (e: any) => {
  router.push({ name: 'VolunteerRecruitNoticeDetail', query: { id: e.id } })
}

const handleAdd = () => {
  router.push({ name: 'VolunteerRecruitNoticeAdd' })
}

const againChange = async() => {
  if (type.value == 'down') {
    try {
      const [error, data] = await sendRequest({
        module: 'volunteer',
        api: 'updateStatusDown',
        override: {
          data: editData
        }
      });
      if (error) throw new Error(error.message)
      if (data.code !== 0) throw new Error(data.msg)
      message.success('操作成功');
      visible.value = false;
      queryTableData();
    } catch (error: any) {
      message.error(error.message)
    }
  } else {
    try {
      const [error, data] = await sendRequest({
        module: 'volunteer',
        api: 'updateStatusUp',
        override: {
          data: editData
        }
      });
      if (error) throw new Error(error.message)
      if (data.code !== 0) throw new Error(data.msg)
      message.success('操作成功');
      visible.value = false;
      queryTableData();
    } catch (error: any) {
      message.error(error.message)
    }
  }
}
const editData = reactive({});
const handleListFlagStatus = async(e: any) => {
  let {
    listFlag
  } = e;
  Object.assign(editData, e);
  if (listFlag == 1) {
    type.value = 'down';
  } else {
    type.value = 'up';
  }
  visible.value = true;
}

const ids = ref()
const handleDelete = async (id: any) => {
  ids.value = id
  modalVisible.value = true
  // const [error, res] = await sendRequest<HttpResponse>({
  //   module: 'volunteer',
  //   api: 'delete',
  //   override: {
  //     data: [id]
  //   }
  // })
  // if (error) return message.error(error.message)
  // if (res.code !== 0) {
  //   message.error(res.msg)
  // } 
  // else {
  //   message.success('删除成功')
  // }
  // queryTableData()
}
const againDelete = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'delete',
    override: {
      data: [ids.value]
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) {
    message.error(res.msg)
  } else {
    message.success('删除成功')
    queryTableData(true)
    modalVisible.value = false
  }
}
onMounted(() => {
  queryTableData(true)
})
const actionId = ref<any>('');
const handleChangeSort = (val:number, type: string) => {
  action.value = type;
  actionId.value = val;
  modal.value = true;
}


const againAction = async() => {
  if (action.value == 'up') {
    handleNoticeSortUp(actionId.value)
  } else {
    handleNoticeSortDown(actionId.value)
  }
}

const handleNoticeSortUp = async(val:number) => {
  const [error, res] = await sendRequest<HttpResponsePagination<any>>({
    module: 'volunteer',
    api: 'recruitNoticeSortUp',
    uri: {
      id: val
    }
  })
  if (error) throw new Error(error.message)
  if (res.code !== 0) throw new Error(res.msg)
  message.success('操作成功')
  modal.value = false;
  queryTableData(true)
}

const handleNoticeSortDown = async(val:number) => {
  const [error, res] = await sendRequest<HttpResponsePagination<any>>({
    module: 'volunteer',
    api: 'recruitNoticeSortDown',
    uri: {
      id: val
    }
  })
  if (error) throw new Error(error.message)
  if (res.code !== 0) throw new Error(res.msg)
  message.success('操作成功')
  modal.value = false;
  queryTableData(true)
}
watch(
  () => route,
  () => {
    if (
      route.path == '/volunteer/recruit/notice/index'
    ) {
      queryTableData(true)
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
.noticeBox {
  padding: 16px 16px 99px 16px;
}
.noticeMain {
}
.previewView {
  width: 375px;
  height: 75vh;
  padding-bottom: 80px;
  background: #f5f5f5;
  border-radius: 25px;
  overflow: hidden;
  background-image: url('@/assets/images/app_bg.jpg');
}
.previewViewTitle {
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 16px;
  color: #ffffff;
  background-color: #048c5e;
}
.previewViewContent {
  box-sizing: border-box;
  height: calc(75vh - 80px);
  overflow-y: scroll;
  overflow-x: hidden;
  background: rgba(255,255,255,0.5);
  border-radius: 16px;
  padding: 0px 24px;
  overflow-y: scroll;
  box-sizing: border-box;
}
.previewViewFooter {
  width: 340px;
  height: 36px;
  margin-top: 4px;
  background: #326C53;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 25px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #FFFFFF;
}
</style>
